package com.lhkk.inventoryvehicle.camera // 使用您原来的包名

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.graphics.Matrix
import android.graphics.RectF
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureFailure
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.TotalCaptureResult
import android.media.ImageReader
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Size
import android.view.*
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.cj.mvvmlib.base.activity.BaseVmActivity
import com.cj.mvvmlib.base.viewmodel.BaseViewModel
import com.cj.mvvmlib.databinding.ActivityCamera2Binding
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class Camera2Activity : BaseVmActivity<BaseViewModel>() {

    private lateinit var camera2Binding: ActivityCamera2Binding

    private val TAG = "Camera2Kotlin"
    private val REQUEST_CAMERA_PERMISSION = 1
    private val REQUEST_STORAGE_PERMISSION = 2

    private var cameraId: String = "0" // 将在 openCamera 中动态设置
    private var cameraDevice: CameraDevice? = null
    private var cameraCaptureSession: CameraCaptureSession? = null
    private var captureRequestBuilder: CaptureRequest.Builder? = null // 用于预览
    private lateinit var imageDimension: Size // 预览尺寸
    private var imageReader: ImageReader? = null

    private var backgroundThread: HandlerThread? = null
    private var backgroundHandler: Handler? = null

    private var orientationEventListener: OrientationEventListener? = null
    private var currentDisplayRotation: Int = -1 // 存储当前显示旋转角度 (0, 90, 180, 270)


    // TextureView 监听器
    private val textureListener = object : TextureView.SurfaceTextureListener {
        override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
            openCamera(width, height)
        }

        override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
            configureTransform(width, height)
        }

        override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
            closeCamera()
            return true
        }

        override fun onSurfaceTextureUpdated(surface: SurfaceTexture) { // 预览帧更新时的回调
        }
    }

    // CameraDevice 状态回调
    private val stateCallback = object : CameraDevice.StateCallback() {
        override fun onOpened(camera: CameraDevice) {
            Log.d(TAG, "相机已打开: ${camera.id}")
            cameraDevice = camera
            createCameraPreviewSession()
        }

        override fun onDisconnected(camera: CameraDevice) {
            Log.w(TAG, "相机已断开连接")
            cameraDevice?.close()
            cameraDevice = null
        }

        override fun onError(camera: CameraDevice, error: Int) {
            Log.e(TAG, "相机打开错误: $error")
            cameraDevice?.close()
            cameraDevice = null
            this@Camera2Activity.finish()
        }
    }

    override fun useTitleBar(): Boolean {
        return false
    }

    override fun layoutId(): View {
        camera2Binding = ActivityCamera2Binding.inflate(layoutInflater)
        return camera2Binding.root
    }

    override fun initView(savedInstanceState: Bundle?) {
        currentDisplayRotation = getDisplaySurfaceRotation(windowManager.defaultDisplay.rotation)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.CAMERA),
                REQUEST_CAMERA_PERMISSION)
        } else {
            camera2Binding.previewSv.surfaceTextureListener = textureListener
        }

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_STORAGE_PERMISSION)
            }
        }

        camera2Binding.setBt.setOnClickListener {
            takePicture()
        }

        orientationEventListener = object : OrientationEventListener(this) {
            override fun onOrientationChanged(orientation: Int) {
                if (orientation == ORIENTATION_UNKNOWN) return
                val newRotation = getDisplaySurfaceRotation(windowManager.defaultDisplay.rotation)
                if (currentDisplayRotation != newRotation) {
                    currentDisplayRotation = newRotation
                    Log.d(TAG, "设备方向改变，新的旋转角度: $currentDisplayRotation")
                    if (camera2Binding.previewSv.isAvailable && ::imageDimension.isInitialized && imageDimension != null) {
                        configureTransform(camera2Binding.previewSv.width,
                            camera2Binding.previewSv.height)
                    }
                }
            }
        }
    }

    override fun initData() {}
    override fun setListener() {}
    override fun createObserver() {}

    private fun startBackgroundThread() {
        backgroundThread = HandlerThread("CameraBackground").also { it.start() }
        backgroundThread?.looper?.let { backgroundHandler = Handler(it) }
    }

    private fun stopBackgroundThread() {
        backgroundThread?.quitSafely()
        try {
            backgroundThread?.join()
            backgroundThread = null
            backgroundHandler = null
        } catch (e: InterruptedException) {
            Log.e(TAG, "停止后台线程错误", e)
        }
    }

    private fun openCamera(viewWidth: Int, viewHeight: Int) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "未授予相机权限", Toast.LENGTH_SHORT).show()
            return
        }

        val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            var preferredCameraId: String? = null
            var foundFront = false
            var foundBack = false

            for (camId in manager.cameraIdList) {
                val characteristics = manager.getCameraCharacteristics(camId)
                val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
                if (facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    preferredCameraId = camId
                    foundFront = true
                    break
                }
            }

            if (!foundFront) {
                for (camId in manager.cameraIdList) {
                    val characteristics = manager.getCameraCharacteristics(camId)
                    val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
                    if (facing == CameraCharacteristics.LENS_FACING_BACK) {
                        preferredCameraId = camId
                        foundBack = true
                        break
                    }
                }
            }

            if (preferredCameraId == null && manager.cameraIdList.isNotEmpty()) {
                preferredCameraId = manager.cameraIdList[0]
            }

            if (preferredCameraId == null) {
                Log.e(TAG, "未找到可用摄像头")
                Toast.makeText(this, "未找到可用摄像头", Toast.LENGTH_SHORT).show()
                return
            }
            cameraId = preferredCameraId
            Log.i(TAG, "选用的摄像头 ID: $cameraId, 是否前置: $foundFront, 是否后置: $foundBack")

            val characteristics = manager.getCameraCharacteristics(cameraId!!)
            val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
            imageDimension = chooseOptimalSize(map.getOutputSizes(SurfaceTexture::class.java),
                viewWidth,
                viewHeight)

            val largestJpegSize = map.getOutputSizes(ImageFormat.JPEG)
                .maxWithOrNull(compareBy { it.height.toLong() * it.width })
            if (largestJpegSize != null) {
                Log.i(TAG, "选用的照片尺寸: ${largestJpegSize.width}x${largestJpegSize.height}")
                imageReader = ImageReader.newInstance(largestJpegSize.width,
                    largestJpegSize.height,
                    ImageFormat.JPEG,
                    1 // 只缓存一张图片
                )
                imageReader?.setOnImageAvailableListener({ reader ->
                    val image = reader.acquireLatestImage()
                    if (image != null) {
                        val buffer = image.planes[0].buffer
                        val bytes = ByteArray(buffer.remaining())
                        buffer.get(bytes)
                        saveImage(bytes)
                        image.close()
                    } else {
                        Log.w(TAG, "ImageReader aacquirLatestImage() returned null")
                    }
                }, backgroundHandler)
            } else {
                Log.e(TAG, "无法获取JPEG输出尺寸")
                Toast.makeText(this, "无法配置拍照功能", Toast.LENGTH_SHORT).show()
                return
            }

            manager.openCamera(cameraId!!, stateCallback, backgroundHandler)
            if (viewWidth > 0 && viewHeight > 0) {
                configureTransform(viewWidth, viewHeight)
            }
        } catch (e: CameraAccessException) {
            Log.e(TAG, "打开相机失败", e)
            Toast.makeText(this, "打开相机失败", Toast.LENGTH_SHORT).show()
        } catch (e: SecurityException) {
            Log.e(TAG, "相机权限不足", e)
            Toast.makeText(this, "相机权限不足", Toast.LENGTH_SHORT).show()
        }
    }

    private fun chooseOptimalSize(choices: Array<Size>,
        textureViewWidth: Int,
        textureViewHeight: Int): Size {
        val bigEnough = ArrayList<Size>()
        val notBigEnough = ArrayList<Size>()

        if (textureViewWidth == 0 || textureViewHeight == 0) {
            Log.w(TAG, "TextureView 尺寸为0，无法精确选择预览尺寸，返回第一个可用尺寸")
            return choices.firstOrNull() ?: Size(640, 480)
        }

        for (option in choices) {
            if (option.width <= textureViewWidth && option.height <= textureViewHeight && option.height == option.width * textureViewHeight / textureViewWidth) {
                if (option.width >= textureViewWidth && option.height >= textureViewHeight) {
                    bigEnough.add(option)
                } else {
                    notBigEnough.add(option)
                }
            }
        }
        if (bigEnough.isNotEmpty()) {
            return Collections.min(bigEnough, CompareSizesByArea())
        } else if (notBigEnough.isNotEmpty()) {
            return Collections.max(notBigEnough, CompareSizesByArea())
        } else {
            Log.w(TAG, "找不到完全匹配宽高比的预览尺寸，选择面积最大的可用尺寸")
            val suitableSizes =
                choices.filter { it.width <= textureViewWidth && it.height <= textureViewHeight }
            return suitableSizes.maxWithOrNull(CompareSizesByArea()) ?: choices.firstOrNull()
            ?: Size(640, 480)
        }
    }

    private fun configureTransform(viewWidth: Int, viewHeight: Int) {
        if (!::imageDimension.isInitialized || imageDimension == null || cameraId == null || cameraDevice == null || viewWidth == 0 || viewHeight == 0) {
            Log.w(TAG,
                "configureTransform: Not ready - imageDimension, cameraId, cameraDevice is null, or view dimensions are zero.")
            return
        }
        val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val characteristics: CameraCharacteristics
        try {
            characteristics = manager.getCameraCharacteristics(cameraId)
        } catch (e: CameraAccessException) {
            Log.e(TAG, "获取相机特性失败 for cameraId: $cameraId", e)
            return
        }

        val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
        val lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING)
        val displayRotationDegrees = currentDisplayRotation

        val matrix = Matrix()
        val viewRect = RectF(0f, 0f, viewWidth.toFloat(), viewHeight.toFloat())
        val centerX = viewRect.centerX()
        val centerY = viewRect.centerY()

        val totalRotation = (sensorOrientation - displayRotationDegrees + 360) % 360

        val effectivePreviewWidth =
            if (totalRotation == 90 || totalRotation == 270) imageDimension.height.toFloat() else imageDimension.width.toFloat()
        val effectivePreviewHeight =
            if (totalRotation == 90 || totalRotation == 270) imageDimension.width.toFloat() else imageDimension.height.toFloat()

        if (effectivePreviewWidth == 0f || effectivePreviewHeight == 0f) {
            Log.e(TAG, "Effective preview dimensions are zero, cannot configure transform.")
            return
        }

        val scaleX = viewWidth.toFloat() / effectivePreviewWidth
        val scaleY = viewHeight.toFloat() / effectivePreviewHeight
        val actualScaleFactor = Math.max(scaleX, scaleY)

        val finalScaleAppliedToOriginalPreviewX =
            actualScaleFactor * effectivePreviewWidth / imageDimension.width.toFloat()
        val finalScaleAppliedToOriginalPreviewY =
            actualScaleFactor * effectivePreviewHeight / imageDimension.height.toFloat()

        matrix.postScale(finalScaleAppliedToOriginalPreviewX,
            finalScaleAppliedToOriginalPreviewY,
            centerX,
            centerY)
        matrix.postRotate(-totalRotation.toFloat(), centerX, centerY)

        if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT) {
            matrix.postScale(-1f, 1f, centerX, centerY)
            Log.d(TAG, "应用前置摄像头镜像.")
        }

        camera2Binding.previewSv.setTransform(matrix)
        Log.d(TAG,
            "Transform configured. TotalRotation: $totalRotation, View: $viewWidth x $viewHeight, Preview: ${imageDimension.width}x${imageDimension.height}, Lens: $lensFacing, ScaleFactor: $actualScaleFactor")
    }


    private fun createCameraPreviewSession() {
        try {
            if (!::imageDimension.isInitialized || imageDimension == null) {
                Log.e(TAG, "createCameraPreviewSession: imageDimension is not initialized.")
                if (camera2Binding.previewSv.isAvailable) {
                    openCamera(camera2Binding.previewSv.width, camera2Binding.previewSv.height)
                }
                return
            }

            val texture = camera2Binding.previewSv.surfaceTexture ?: return
            texture.setDefaultBufferSize(imageDimension.width, imageDimension.height)
            val surface = Surface(texture)

            captureRequestBuilder =
                cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
            captureRequestBuilder?.addTarget(surface)

            val characteristics =
                (getSystemService(Context.CAMERA_SERVICE) as CameraManager).getCameraCharacteristics(
                    cameraId)
            val afModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES)
            if (afModes?.contains(CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) == true) {
                captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
            } else if (afModes?.contains(CaptureRequest.CONTROL_AF_MODE_AUTO) == true) {
                captureRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_AUTO)
            }

            val awbModes = characteristics.get(CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES)
            if (awbModes?.contains(CaptureRequest.CONTROL_AWB_MODE_AUTO) == true) {
                captureRequestBuilder?.set(CaptureRequest.CONTROL_AWB_MODE,
                    CaptureRequest.CONTROL_AWB_MODE_AUTO)
            }

            val aeModes = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES)
            if (aeModes?.contains(CaptureRequest.CONTROL_AE_MODE_ON) == true) {
                captureRequestBuilder?.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON)
            }

            cameraDevice?.createCaptureSession(listOf(surface,
                imageReader?.surface).filterNotNull(),
                object : CameraCaptureSession.StateCallback() {
                    override fun onConfigured(session: CameraCaptureSession) {
                        if (cameraDevice == null) return
                        cameraCaptureSession = session
                        try {
                            captureRequestBuilder?.build()?.let {
                                cameraCaptureSession?.setRepeatingRequest(it,
                                    null,
                                    backgroundHandler)
                            }

                        } catch (e: CameraAccessException) {
                            Log.e(TAG, "创建预览失败", e)
                        } catch (e: IllegalStateException) {
                            Log.e(TAG, "创建预览失败，会话已关闭或设备已断开", e)
                        }
                    }

                    override fun onConfigureFailed(session: CameraCaptureSession) {
                        Log.e(TAG, "配置相机预览失败")
                        Toast.makeText(this@Camera2Activity, "配置相机预览失败", Toast.LENGTH_SHORT)
                            .show()
                    }
                },
                backgroundHandler)
        } catch (e: CameraAccessException) {
            Log.e(TAG, "创建预览会话错误", e)
        } catch (e: IllegalStateException) {
            Log.e(TAG, "创建预览会话错误，设备可能已关闭", e)
        } catch (e: NullPointerException) {
            Log.e(TAG, "创建预览会话时发生空指针异常 (可能 imageDimension 未正确初始化)", e)
        }
    }

    private fun takePicture() {
        if (cameraDevice == null || imageReader == null || captureRequestBuilder == null) {
            Log.e(TAG, "相机设备、ImageReader 或预览请求构建器未初始化")
            Toast.makeText(this, "相机未准备好", Toast.LENGTH_SHORT).show()
            return
        }

        try {
            val characteristics =
                (getSystemService(Context.CAMERA_SERVICE) as CameraManager).getCameraCharacteristics(
                    cameraId)

            val captureBuilder =
                cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
            imageReader?.surface?.let { captureBuilder?.addTarget(it) }

            // --- 开始：提升照片质量的设置 ---
            captureBuilder?.set(CaptureRequest.JPEG_QUALITY, 95.toByte())

            val availableNoiseReductionModes =
                characteristics.get(CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES)
            if (availableNoiseReductionModes?.contains(CaptureRequest.NOISE_REDUCTION_MODE_HIGH_QUALITY) == true) {
                captureBuilder?.set(CaptureRequest.NOISE_REDUCTION_MODE,
                    CaptureRequest.NOISE_REDUCTION_MODE_HIGH_QUALITY)
                Log.d(TAG, "降噪模式设置为: HIGH_QUALITY")
            }

            val availableEdgeModes =
                characteristics.get(CameraCharacteristics.EDGE_AVAILABLE_EDGE_MODES)
            if (availableEdgeModes?.contains(CaptureRequest.EDGE_MODE_HIGH_QUALITY) == true) {
                captureBuilder?.set(CaptureRequest.EDGE_MODE, CaptureRequest.EDGE_MODE_HIGH_QUALITY)
                Log.d(TAG, "边缘模式设置为: HIGH_QUALITY")
            }

            // 4. 光学防抖 (OIS) - 如果可用
            // 正确的 CameraCharacteristics Key 用于获取可用的OIS模式
            val availableOisModes =
                characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION)
            if (availableOisModes != null && availableOisModes.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)) {
                captureBuilder?.set(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE,
                    CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)
                Log.d(TAG, "光学防抖设置为: ON")
            } else {
                Log.d(TAG,
                    "光学防抖 (OIS) 不可用或不支持 ON 模式。Available modes: ${availableOisModes?.joinToString()}")
            } // --- 结束：提升照片质量的设置 ---

            captureBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
                captureRequestBuilder?.get(CaptureRequest.CONTROL_AF_MODE)
                    ?: CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
            captureBuilder?.set(CaptureRequest.CONTROL_AWB_MODE,
                captureRequestBuilder?.get(CaptureRequest.CONTROL_AWB_MODE)
                    ?: CaptureRequest.CONTROL_AWB_MODE_AUTO)
            captureBuilder?.set(CaptureRequest.CONTROL_AE_MODE,
                captureRequestBuilder?.get(CaptureRequest.CONTROL_AE_MODE)
                    ?: CaptureRequest.CONTROL_AE_MODE_ON)

            val jpegOrientation =
                getJpegOrientation(characteristics, windowManager.defaultDisplay.rotation)
            captureBuilder?.set(CaptureRequest.JPEG_ORIENTATION, jpegOrientation)
            Log.d(TAG, "设置JPEG方向为: $jpegOrientation")

            val captureCallback = object : CameraCaptureSession.CaptureCallback() {
                override fun onCaptureCompleted(session: CameraCaptureSession,
                    request: CaptureRequest,
                    result: TotalCaptureResult) {
                    super.onCaptureCompleted(session, request, result)
                    Log.d(TAG, "照片捕获完成")
                    restartPreview()
                }

                override fun onCaptureFailed(session: CameraCaptureSession,
                    request: CaptureRequest,
                    failure: CaptureFailure) {
                    super.onCaptureFailed(session, request, failure)
                    Log.e(TAG, "照片捕获失败: ${failure.reason}")
                    Toast.makeText(this@Camera2Activity, "拍照失败", Toast.LENGTH_SHORT).show()
                    restartPreview()
                }
            }

            cameraCaptureSession?.stopRepeating()
            captureBuilder?.build()?.let {
                cameraCaptureSession?.capture(it, captureCallback, backgroundHandler)
            }
        } catch (e: CameraAccessException) {
            Log.e(TAG, "拍照错误", e)
            restartPreview()
        } catch (e: IllegalStateException) {
            Log.e(TAG, "拍照错误，会话已关闭或设备已断开", e)
            restartPreview()
        }
    }

    private fun restartPreview() {
        try {
            if (cameraDevice != null && cameraCaptureSession != null && cameraCaptureSession?.device == cameraDevice && captureRequestBuilder != null) {
                captureRequestBuilder?.build()?.let {
                    cameraCaptureSession?.setRepeatingRequest(it, null, backgroundHandler)
                }
            } else {
                Log.w(TAG, "无法重启预览: 相机设备、会话无效或预览请求未初始化")
                if (camera2Binding.previewSv.isAvailable) {
                    openCamera(camera2Binding.previewSv.width, camera2Binding.previewSv.height)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "拍照后重新启动预览失败", e)
        }
    }


    private fun saveImage(bytes: ByteArray) {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "IMG_$timeStamp.jpg"
        val storageDir: File? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        } else {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            } else {
                Log.w(TAG, "无写入外部存储权限，保存到应用专属目录")
                getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            }
        }

        if (storageDir == null) {
            Log.e(TAG, "无法获取存储目录")
            runOnUiThread { Toast.makeText(this, "无法获取存储目录", Toast.LENGTH_LONG).show() }
            return
        }

        if (!storageDir.exists() && !storageDir.mkdirs()) {
            Log.e(TAG, "无法创建目录: ${storageDir.absolutePath}")
            val appSpecificDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            if (appSpecificDir != null) {
                if (!appSpecificDir.exists()) appSpecificDir.mkdirs()
                val imageFile = File(appSpecificDir, fileName)
                saveToFile(bytes, imageFile)
            } else {
                Log.e(TAG, "应用专属目录也无法访问")
                runOnUiThread {
                    Toast.makeText(this, "无法保存图片: 存储错误", Toast.LENGTH_LONG).show()
                }
            }
            return
        }

        val imageFile = File(storageDir, fileName)
        saveToFile(bytes, imageFile)
    }

    private fun saveToFile(bytes: ByteArray, file: File) {
        var output: FileOutputStream? = null
        try {
            output = FileOutputStream(file)
            output.write(bytes)
            Log.d(TAG, "图片已保存: ${file.absolutePath}")
            runOnUiThread {
                Toast.makeText(this, "图片保存在: ${file.name}", Toast.LENGTH_SHORT).show()
            }
        } catch (e: IOException) {
            Log.e(TAG, "保存图片失败", e)
            runOnUiThread { Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show() }
        } finally {
            output?.close()
        }
    }

    private fun closeCamera() {
        try {
            cameraCaptureSession?.close()
            cameraCaptureSession = null
        } catch (e: Exception) {
            Log.e(TAG, "关闭相机 CaptureSession 时出错", e)
        }
        try {
            cameraDevice?.close()
            cameraDevice = null
        } catch (e: Exception) {
            Log.e(TAG, "关闭 CameraDevice 时出错", e)
        }
        try {
            imageReader?.close()
            imageReader = null
        } catch (e: Exception) {
            Log.e(TAG, "关闭 ImageReader 时出错", e)
        }
        Log.d(TAG, "相机资源已关闭")
    }

    override fun onResume() {
        super.onResume()
        startBackgroundThread()
        if (orientationEventListener?.canDetectOrientation() == true) {
            orientationEventListener?.enable()
        } else {
            Log.w(TAG, "方向监听器无法检测方向")
        }

        if (camera2Binding.previewSv.isAvailable) {
            openCamera(camera2Binding.previewSv.width, camera2Binding.previewSv.height)
        } else {
            camera2Binding.previewSv.surfaceTextureListener = textureListener
        }
    }

    override fun onPause() {
        orientationEventListener?.disable()
        closeCamera()
        stopBackgroundThread()
        super.onPause()
    }

    override fun onRequestPermissionsResult(requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                camera2Binding.previewSv.surfaceTextureListener = textureListener
                if (camera2Binding.previewSv.isAvailable) {
                    openCamera(camera2Binding.previewSv.width, camera2Binding.previewSv.height)
                }
            } else {
                Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        } else if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (!(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(this, "存储权限被拒绝，可能无法保存照片到公共目录", Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    private fun getDisplaySurfaceRotation(displayRotationConst: Int): Int {
        return when (displayRotationConst) {
            Surface.ROTATION_0 -> 0
            Surface.ROTATION_90 -> 90
            Surface.ROTATION_180 -> 180
            Surface.ROTATION_270 -> 270
            else -> 0
        }
    }

    private fun getJpegOrientation(characteristics: CameraCharacteristics,
        deviceDisplayRotation: Int): Int {
        val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
        val displayRotationDegrees = getDisplaySurfaceRotation(deviceDisplayRotation)

        val jpegOrientation = (sensorOrientation - displayRotationDegrees + 360) % 360
        Log.d(TAG,
            "Sensor: $sensorOrientation, DisplayRotDeg: $displayRotationDegrees, JpegOrient: $jpegOrientation")
        return jpegOrientation
    }

    internal class CompareSizesByArea : Comparator<Size> {
        override fun compare(lhs: Size, rhs: Size): Int {
            return java.lang.Long.signum(lhs.width.toLong() * lhs.height - rhs.width.toLong() * rhs.height)
        }
    }
}